<#import "/macro.ftl" as m>
<@m.page_header title='资质荣誉' />
<div id="page-content-wrapper">
    <div id="page-title">
        <h3>资质荣誉</h3>
        <div id="breadcrumb-right">
            <div class="float-right">
                <a href="javascript:;" class="btn medium primary-bg" onclick="showAdd();">
                    <span class="button-content">资质荣誉</span>
                </a>
            </div>
        </div>
    </div>
    <div id="page-content">
    	<form id="form" action="/honor" method="get">
    		<div class="form-row">
    			<div class="form-input col-md-6">
    				<input placeholder="填写标题查询" type="text" name="title" id="title" value="${title}">
    			</div>
    			<div class="form-input col-md-2">
		        	<a href="javascript:;" class="btn large primary-bg radius-all-4" id="search" title="Validate!" onclick="$('#form').trigger('submit');">
			            <span class="button-content">查询</span>
	                </a>
		        </div>
    		</div>
    	</form>
    	<table id="honor" class="table">
	        <thead>
	            <tr>
	                <th>标题</th>
	                <th>图片</th>
	                <th>操作</th>
	            </tr>
	        </thead>
	        <tbody>
	        	<tr id="honor-row-template" class="hide">
	                <td id="title"></td>
	                <td id="picture"></td>
	                <td>
	                    <a id="delete" href="javascript:;" class="btn medium primary-bg"">
	                    	<span class="button-content">删除</span>
	                    </a>
	                </td>
	            </tr>
	        	<#list honors.list as honor>
					<tr id="${honor.id}">
						<td>${honor.title}</td>
		                <td><img width="600" heigth="600" src="${honor.picture}"></td>
		                <td>
		                    <a href="javascript:;" class="btn medium primary-bg" onclick="showDelete(${honor.id});">
		                    	<span class="button-content">删除</span>
		                    </a>
		                </td>
		            </tr>
				</#list>    
	    	</tbody>
	    </table>
	    <div class="button-group center-div">
	    	${pagerHelper.content}
	    </div>
    </div>
</div>
<div id="add-honor-template" class="hide">
	<form>
		<div class="form-row">
			<div class="form-label col-md-2">
                <label for="title">标题:</label>
            </div>
            <div class="form-input col-md-10">
                <input name="title" data-required="true" type="text">
            </div>
		</div>
		<div class="form-row">
			<div class="form-label col-md-2">
                <label for="title">图片:</label>
            </div>
			<div class="form-input col-md-10">
		    	<div class="row">
		    		<div class="col-md-8">
		    			<input type="text" name="picture" id="picture"> 
		    		</div>
		    		<div class="form-label col-md-2">
						<a href="javascript:;" class="btn medium primary-bg radius-all-4" onclick="triggerFileupload('image-input');">
					         <span class="button-content">上传图片</span>
	                    </a>
	                    <input id="image-input" type="file" name="images" multiple="" class="hide">
                    </div>
	            </div>
		    </div>
		</div>
	</form>
</div>

<script type="text/javascript" src="/assets/js/md5.js"></script>
<script type="text/javascript" src="/assets/js/uuid.core.js"></script>
<script src="/assets/multiupload/jquery.iframe-transport.js"></script>
<script src="/assets/multiupload/jquery.fileupload.js"></script>
<script type="text/javascript">

// 触发上传图片
function triggerFileupload( imageInputId ) {

	$( '#' + imageInputId ).fileupload({
        dataType: 'json',
        add: function (e, data) {
            uploadToUpyun(data.files[0], function(url){
            	$("#dialog #picture").val(url);
            });
        }
    });
    
    $( '#' + imageInputId ).trigger('click');
}

function uploadToUpyun(file, success) {

    $.get("/upyun/bucketapi", function (data) {

        var config = {
            api: 'http://v0.api.upyun.com/',
            bucket: data.bucket,
            // 空间的表单 API
            form_api: data.formId
        };
        
        if (!file) {
            console.log('no file is selected');
            return;
        }
        
        var date = new Date();
        var dir = "upload/images/honor/" + date.getFullYear() + "/" + (date.getMonth() + 1) + "/";
        var fileName = UUID.generate() + '.png';
        
        // 计算 policy 和 signature 所需的参数
        // 详情见： http://docs.upyun.com/api/form_api/#表单API接口简介
        var options = {
            bucket: config.bucket,
            expiration: Math.floor(new Date().getTime() / 1000) + 86400,
            'save-key': dir + fileName
        };

        var policy = window.btoa(JSON.stringify(options));
        var signature = CryptoJS.MD5(policy + '&' + config.form_api);

        var dataform = new FormData();
        dataform.append('policy', policy);
        dataform.append('signature', signature);
        dataform.append('file', file);

        var request = new XMLHttpRequest();
        request.open('POST', config.api + options.bucket);

        request.onload = function (e) {
        	
            var jsonResponse = JSON.parse(request.response);
            if (jsonResponse.code == "200") {
                var uploadUrl = data.returnUrl + '/'+ dir + fileName;
                if(success){
                	success(uploadUrl);
                }
				
                $.jGrowl("上传又拍云成功", {sticky: !1, position: "top-right", theme: "bg-green"});
            } else {
                $.jGrowl("上传又拍云失败，错误代码" + jsonResponse.code, {sticky: !1, position: "top-right", theme: "bg-green"});
            }
        };

        request.send(dataform);
    });
}

function showAdd(){
	var html = '<div id="dialog" class="hide" title="添加资质荣誉"><div class="mrg10A">' + $("#add-honor-template").html() + '</div></div>';
	$( html ).dialog({
        resizable:!0,
        minWidth:600,
        minHeight:250,
        modal:!0,
        dialogClass:"modal-dialog",
        closeOnEscape:!0,
        close : function() {
			$( this ).dialog( "destroy" );
		},
        buttons: {
            保存: function() {
            	var valid = $('#dialog form').parsley( 'validate' );
            	if(!valid){
            		return;
            	}
            	
            	$.post( '/honor', $( '#dialog form' ).serialize() )
                 .done(function(data){
                 	if(data["status"] == "success"){
                 		$.jGrowl("添加资质荣誉成功", {sticky:!1,position:"top-right",theme:"bg-green"});
                 		$( "#dialog" ).dialog( "close" );
                 		location.reload();
                 	}else{
                 		$.jGrowl(data["message"], {sticky:!1,position:"top-right",theme:"bg-red"});
                 	}
                 })
                 .fail(function(){
                 	$.jGrowl("添加资质荣誉失败", {sticky:!1,position:"top-right",theme:"bg-red"});
                 	$( "#dialog" ).dialog( "close" );
                 });
            }
		}
	});
};

function showDelete( id ){
	$.messager.confirm( "提示", "确定删除吗？", function(){
		$.ajax({
		    url: '/honor/' + id,
		    type: 'POST',
		    data: { _method: 'DELETE' }
		})
	    .done(function(data){
	     	if(data["status"] == "success"){
	     		$.jGrowl("删除资质荣誉成功", {sticky:!1,position:"top-right",theme:"bg-green"});
	     		$('.table').find('tr[id=' + id + ']').remove();
	     	}else{
	     		$.jGrowl(data["message"], {sticky:!1,position:"top-right",theme:"bg-red"});
	     	}
	     })
	     .fail(function(){
	     	$.jGrowl("删除资质荣誉失败", {sticky:!1,position:"top-right",theme:"bg-red"});
	     });
	});
};

</script>